<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="类型" prop="quType">
        <el-select v-model="queryParams.quType" placeholder="请选择题目类型" clearable>
          <el-option v-for="item in this.$store.state.titleName.questionType" :key="item.id" :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="设备" prop="level">
        <el-select v-model="queryParams.level" placeholder="请选择设备" clearable @change="changeQuesBank">
          <el-option v-for="item in equipmentBank" :key="item.id" :label="item.equipmentName"
            :value="item.id"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="题库" prop="quBankId">
        <el-select v-model="queryParams.quBankId" placeholder="请选择题库" clearable>
          <el-option v-for="item in allBank" :key="item.id" :label="item.bankName" :value="item.id"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>

    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="getAdd"
          v-hasPermi="['system:question:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:question:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['system:question:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="questionList" @selection-change="handleSelectionChange"
      @row-dblclick="handleTableRow">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column v-if="false" label="id" align="center" prop="id" />
      <el-table-column label="题目类型" align="center">
        <template slot-scope="scope">
          {{ typeIdToName(scope.row.quType) }}
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip="true" label="题目内容" align="center" prop="quContent" />
      <el-table-column label="设备" align="center" prop="pquestionEquipmentBank.equipmentName" />
      <el-table-column label="所属题库" align="center" prop="pquestionBank.bankName" />
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="updateQu(scope.row.id, scope.row.quType)"
            v-hasPermi="['system:question:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:question:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改试题对话框 -->
    <el-dialog title="更新题目" :visible.sync="updateQuTableVisible" width="50%" center>
      <el-card>
        <el-form :model="updateQuForm" ref="updateQuForm" :rules="updateQuFormRules">
          <el-form-item label="题目类型" label-width="120px" prop="questionType">
            <el-select v-model="updateQuForm.questionType" disabled @change="updateQuForm.answer = []" placeholder="请选择">
              <el-option v-for="item in this.$store.state.titleName.questionType" :key="item.id" :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="仪器" label-width="120px" prop="questionLevel">
            <el-select v-model="updateQuForm.questionLevel" @change="getQuestionBank" placeholder="请选择" value-key="value">
              <el-option v-for="item in equipmentBank" :key="item.id" :label="item.equipmentName"
                :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="归属题库" label-width="120px" prop="bankId">
            <el-select v-model="updateQuForm.bankId" placeholder="请选择">
              <el-option v-for="item in allBank" :key="item.id" :label="item.bankName" :value="item.id"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item v-if="According" label="B型题分组" label-width="120px">
            <el-select v-model="updateQuForm.quParentId" v-show="!manual" placeholder="请选择">
              <el-option v-for="item in AccordingList" :key="item.id" :label="item.quContent" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="案例实例" v-if="caseExamplesBool" label-width="120px" prop="caseExamples">
            <el-input v-model="updateQuForm.caseExamples" style="margin-left: 5px" type="textarea" :rows="2"></el-input>
          </el-form-item>

          <el-form-item label="题目内容" label-width="120px" prop="questionContent">
            <el-input v-model="updateQuForm.questionContent" style="margin-left: 5px" type="textarea"
              :rows="2"></el-input>
          </el-form-item>

          <el-form-item label="题目图片" label-width="120px">
            <!-- <el-upload
              :action="imgupdate"
              :on-preview="uploadPreview"
              :on-remove="handleUpdateRemove"
              :before-upload="beforeAvatarUpload"
              list-type="picture"
              :on-success="updateUploadImgSuccess"
              name="file"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过10M
              </div>
            </el-upload> -->
          </el-form-item>
          <el-button type="primary" plain size="small" icon="el-icon-plus" style="margin-left: 40px"
            @click="addUpdateAnswer">
            添加
          </el-button>

          <!--存放答案表单的信息-->
          <el-form-item prop="answer">
            <el-table :data="updateQuForm.answer" border style="width: 96%; margin-left: 40px; margin-top: 10px">
              <el-table-column label="是否答案" width="80" align="center">
                <template slot-scope="scope">
                  <el-checkbox v-model="scope.row.isTrue" @change="(checked) => checkUpdateAnswer(checked, scope.row.id)
                    ">答案
                  </el-checkbox>
                </template>
              </el-table-column>
              <el-table-column label="答案内容">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.answer" style="margin-left: 5px" type="textarea" :rows="2"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80" align="center">
                <template slot-scope="scope">
                  <el-button type="danger" icon="el-icon-delete" circle
                    @click="delUpdateAnswer(scope.row.id)"></el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-form>
      </el-card>

      <div slot="footer" class="dialog-footer">
        <el-button @click="updateQuTableVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateQuestion">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 已修改 -->
    <el-dialog title="新增题目" :visible.sync="addQuTableVisible" width="50%" @close="resetAddQuForm" center>
      <el-card>
        <el-form :model="addQuForm" ref="addQuForm" :rules="addQuFormRules">
          <el-form-item label="题目类型" label-width="120px" prop="questionType">
            <el-select v-model="addQuForm.questionType" @change="getType" placeholder="请选择">
              <el-option v-for="item in this.$store.state.titleName.questionType" :key="item.id" :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="仪器" label-width="120px" prop="questionLevel">
            <el-select v-model="addQuForm.questionLevel" @change="getQuestionBank" placeholder="请选择">
              <el-option v-for="item in equipmentBank" :key="item.id" :label="item.equipmentName"
                :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="归属题库" label-width="120px" prop="bankId">
            <el-select v-model="addQuForm.bankId" placeholder="请选择">
              <el-option v-for="item in allBank" :key="item.id" :label="item.bankName" :value="item.id"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item v-show="According" label="B型题分组" label-width="120px">
            <el-select v-model="addQuForm.quParentId" v-show="!manual" placeholder="请选择" @change="assignment">
              <el-option v-for="item in AccordingList" :key="item.id" :label="item.quContent" :value="item.id">
              </el-option>
            </el-select>
            <el-input v-show="manual" v-model="addQuForm.quGeneral" placeholder="请输入"></el-input>
            <el-checkbox style="margin-left: 5%" v-model="manual" @change="getCheckbox">添 加</el-checkbox>
          </el-form-item>
          <el-form-item label="案例实例" v-if="caseExamplesBool" label-width="120px" prop="caseExamples">
            <el-input v-model="addQuForm.caseExamples" style="margin-left: 5px" type="textarea" :rows="2"></el-input>
          </el-form-item>

          <el-form-item label="题目内容" label-width="120px" prop="questionContent">
            <el-input v-model="addQuForm.questionContent" style="margin-left: 5px" type="textarea" :rows="2"></el-input>
          </el-form-item>

          <el-form-item label="题目图片" label-width="120px" prop="image">
            <el-upload :action="imgupdate" :on-preview="uploadPreview" :on-remove="handleRemove"
              :before-upload="beforeAvatarUpload" list-type="picture" :on-success="uploadImgSuccess" name="file"
              :headers="headers">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过10M
              </div>
            </el-upload>
          </el-form-item>

          <el-button type="primary" plain size="small" icon="el-icon-plus" style="margin-left: 40px" @click="addAnswer">
            添加
          </el-button>

          <!--存放答案表单的信息-->
          <el-form-item prop="answer">
            <el-table :data="addQuForm.answer" border style="width: 96%; margin-left: 40px; margin-top: 10px">
              <el-table-column label="是否答案" width="80" align="center">
                <template slot-scope="scope">
                  <el-checkbox v-model="scope.row.isTrue" @change="(checked) => checkAnswer(checked, scope.row.id)">答案
                  </el-checkbox>
                </template>
              </el-table-column>

              <!-- <el-table-column label="答案图片">
                <template slot-scope="scope">
                  <el-upload
                    :limit="1"
                    :action="imgupdate"
                    :on-preview="uploadPreview"
                    :on-remove="handleAnswerRemove"
                    :before-upload="beforeAvatarUpload"
                    list-type="picture"
                    :on-success="
                      (res) => {
                        return uploadAnswerImgSuccess(res, scope.row.id);
                      }
                    "
                    name="file"
                  >
                    <el-button size="small" type="primary">点击上传</el-button>
                  </el-upload>
                </template>
              </el-table-column> -->

              <el-table-column label="答案内容">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.answer" style="margin-left: 5px" type="textarea" :rows="2"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80" align="center">
                <template slot-scope="scope">
                  <el-button type="danger" icon="el-icon-delete" circle @click="delAnswer(scope.row.id)"></el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-form>
      </el-card>

      <div slot="footer" class="dialog-footer">
        <el-button @click="addQuTableVisible = false">取 消</el-button>
        <el-button type="primary" @click="addQuestion">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listQuestion,
  getQuestion,
  delQuestion,
  toAddQuestion,
  toUpdateQuestion,
  getBQuestionGroupName,
} from "@/api/exam/question";
import { getToken } from "@/utils/auth";
//仪器
import { listBank } from "@/api/exam/bank";
//题库
import { listQuestionBank } from "@/api/exam/questionBank";

export default {
  name: "Question",

  data() {
    return {
      imgupdate: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      typeOpts: [{
        value: '1',
        label: '简单'
      }, {
        value: '2',
        label: '中等'
      }, {
        value: '3',
        label: '困难'
      }],

      //仪器
      equipmentBank: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 试题表格数据
      questionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        quContent: null,
        quType: null,
        level: null,
        quBankId: null,
        analysis: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},

      //B型题显示
      According: false,
      //A3/4 是否显示
      caseExamplesBool: false,

      //题库信息
      allBank: [],
      //更新题目表单的验证规则
      updateQuFormRules: {
        questionType: [
          {
            required: true,
            message: "请选择问题类型",
            trigger: "blur",
          },
        ],
        bankId: [
          {
            required: true,
            message: "请选择题库",
            trigger: "blur",
          },
        ],
        questionLevel: [
          {
            required: true,
            message: "请选择仪器",
            trigger: "blur",
          },
        ],
        questionContent: [
          {
            required: true,
            message: "请输入题库内容",
            trigger: "blur",
          },
        ],
        caseExamples: [
          {
            required: true,
            message: "请输入案例实例",
            trigger: "blur",
          },
        ],
      },
      //更新题目的数据信息
      updateQuForm: {
        caseExamples: "",
        quParentId: "",
        quGeneral: "",
        questionId: "",
        questionType: "",
        bankId: "",
        questionContent: "",
        questionLevel: "",
        images: [],
        analysis: "",
        createPerson: localStorage.getItem("username"),
        //答案对象
        answer: [],
      },
      //是否显示更新题目的对话框
      updateQuTableVisible: false,
      //是否显示添加题目的对话框
      addQuTableVisible: false,
      //添加题目的表单信息
      addQuForm: {
        // number: 0,
        quId: "",
        caseExamples: "",
        quGeneral: "",
        quParentId: "",
        questionType: 1,
        bankId: "",
        questionLevel: "",
        questionContent: "",
        images: [],
        analysis: "",
        // createPerson: localStorage.getItem("username"),
        //答案对象
        answer: [],
      },
      //添加题目表单的验证规则
      addQuFormRules: {
        questionType: [
          {
            required: true,
            message: "请选择问题类型",
            trigger: "blur",
          },
        ],
        bankId: [
          {
            required: true,
            message: "请选择题库",
            trigger: "blur",
          },
        ],
        questionLevel: [
          {
            required: true,
            message: "请选择仪器",
            trigger: "blur",
          },
        ],
        questionContent: [
          {
            required: true,
            message: "请输入题库内容",
            trigger: "blur",
          },
        ],
      },
      //是否判断手动填写
      manual: false,
      //B型题数组
      AccordingList: [],
    };
  },
  created() {
    this.getList();
    //仪器
    listBank(null).then((response) => {
      console.log("仪器", response.rows);
      this.equipmentBank = response.rows;
    });
    this.getTypeList();
    this.$store.dispatch('titleName/INIT_NAME');
  },
  methods: {
    /** 双击预览 */
    handleTableRow(row, column, event) {
      console.log("row!!!!", row);
      console.log("id!!!!!", row.id);
      this.updateQu(row.id, true);
    },
    /** 查询试题列表 */
    getList() {
      this.loading = true;
      listQuestion(this.queryParams).then((response) => {
        console.log(response);
        this.questionList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 类型ID转name
    typeIdToName(id) {
      // console.log("id=" + id);
      for (let i = 0; i < this.titleList.length; i++) {
        if (this.titleList[i].id == id) {
          return this.titleList[i].name
        }
      }
      return 'null'
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        quContent: null,
        createPerson: null,
        quType: null,
        level: null,
        image: null,
        quBankId: null,
        quBankName: null,
        analysis: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    changeQuesBank() {
      this.getQuestionBank(this.queryParams.level)
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加试题";
    },
    getAdd() {
      this.addQuForm.caseExamples = "";
      this.addQuTableVisible = true;
      this.addQuForm.quParentId = "";
      this.addQuForm.quGeneral = "";
      this.According = false;
      this.caseExamplesBool = false;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getQuestion(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改试题";
      });
    },
    /** 提交按钮 */
    // submitForm() {
    //   this.$refs["form"].validate((valid) => {
    //     if (valid) {
    //       if (this.form.id != null) {
    //         updateQuestion(this.form).then((response) => {
    //           this.$modal.msgSuccess("修改成功");
    //           this.open = false;
    //           this.getList();
    //         });
    //       } else {
    //         toAddQuestion(this.form).then((response) => {
    //           this.$modal.msgSuccess("新增成功");
    //           this.open = false;
    //           this.getList();
    //         });
    //       }
    //     }
    //   });
    // },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除试题编号为"' + ids + '"的数据项？')
        .then(function () {
          return delQuestion(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/question/export",
        {
          ...this.queryParams,
        },
        `question_${new Date().getTime()}.xlsx`
      );
    },

    //新增题目上传后 点击图片的回显
    uploadPreview(file) {
      this.backShowImgUrl = file.response.data;
      this.backShowImgVisible = true;
    },
    //新增题目中的上传图片的移除
    handleRemove(file, fileList) {
      this.addQuForm.images.map((item, index) => {
        //移除图片在表单中的数据
        if (item === file.response.data) this.addQuForm.images.splice(index, 1);
      });
    },
    //更新题目中的上传图片的移除
    handleUpdateRemove(file, fileList) {
      this.updateQuForm.images.map((item, index) => {
        //移除图片在表单中的数据
        if (item === file.response.data)
          this.updateQuForm.images.splice(index, 1);
      });
    },
    //新增题目中的上传图片的格式大小限制
    beforeAvatarUpload(file) {
      const isImg =
        file.type === "image/jpeg" ||
        file.type === "image/png" ||
        file.type === "image/jpg";
      const isLt = file.size / 1024 / 1024 < 10;

      if (!isImg) {
        this.$message.error("上传图片只能是 JPG/PNG 格式!");
      }

      if (!isLt) {
        this.$message.error("上传头像图片大小不能超过 10MB!");
      }
      return isImg && isLt;
    },
    //新增题目中的上传图片成功后的钩子函数
    uploadImgSuccess(response, file, fileList) {
      console.log("上传图片成功");
      console.log(response);
      this.addQuForm.images.push(response.url);
    },
    //更新题目中的上传图片成功后的钩子函数
    updateUploadImgSuccess(response, file, fileList) {
      this.updateQuForm.images.push(response.data);
    },
    //更新时新增题目中的新增答案填写框
    addUpdateAnswer() {
      this.updateQuForm.answer.push({
        id: this.updateQuForm.answer.length,
        isTrue: false,
        answer: "",
        images: [],
        analysis: "",
      });
    },
    resetAddQuForm() {
      this.$refs["addQuForm"].resetFields();
    },
    //输入框清空
    getCheckbox() {
      console.log("进来");
      this.addQuForm.quGeneral = "";
      this.addQuForm.quParentId = "";
      this.addQuForm.caseExamples = "";
      this.addQuForm.answer = [];
      if (!this.manual) {
        this.getType();
      }
    },
    //新增题目
    addQuestion() {
      //quParentId
      console.log("+++++++", this.addQuForm.quParentId);
      if (
        this.addQuForm.quParentId != "" &&
        this.addQuForm.quParentId != undefined
      ) {
        //获取NAME
        var countId = this.addQuForm.quParentId;
        console.log(countId);
        console.log(this.AccordingList);
        var obj = this.AccordingList.find(function (item) {
          return item.id === countId ? item : 0;
        });
        console.log("圣德芬哈莱克斯顿", obj);
        //重新录入ID
        this.addQuForm.quParentId = obj.quParentId;
        this.addQuForm.quGeneral = obj.quGeneral;
        // = this.AccordingList[this.addQuForm.quParentId].quGeneral;
      }
      this.$refs["addQuForm"].validate((valid) => {
        if (valid && this.addQuForm.answer.some((item) => item.isTrue)) {
          //单选或者多选或者判断n
          console.log("提交+++++++", this.addQuForm);
          toAddQuestion(this.addQuForm).then((response) => {
            this.$modal.msgSuccess("新增成功");
            this.addQuTableVisible = false;
            this.getList();
          });

          // this.$http.post(this.API.addQuestion, this.addQuForm).then((resp) => {
          //   if (resp.data.code === 200) {
          //     this.addQuTableVisible = false;
          //     this.getQuestionInfo();
          //     this.$notify({
          //       title: "Tips",
          //       message: "新增题目成功",
          //       type: "success",
          //       duration: 2000,
          //     });
          //   } else {
          //     this.$notify({
          //       title: "Tips",
          //       message: resp.data.message,
          //       type: "success",
          //       duration: 2000,
          //     });
          //   }
          // });
        } else if (
          valid &&
          !this.addQuForm.answer.some((item) => item.isTrue)
        ) {
          //无答案
          this.$message.error("必须有一个答案");
          return false;
        } else if (!valid) {
          this.$message.error("请填写必要信息");
          return false;
        }
      });
    },
    //新增题目中的新增答案填写框
    addAnswer() {
      this.addQuForm.answer.push({
        id: this.addQuForm.answer.length,
        isTrue: false,
        answer: "",
        images: [],
        analysis: "",
      });
    },
    getType() {
      if (this.addQuForm.questionType === 4) {
        this.According = true;
        this.caseExamplesBool = true;
      } else if (this.addQuForm.questionType === 3) {
        this.caseExamplesBool = true;
      } else {
        this.caseExamplesBool = false;
        this.According = false;
      }
    },
    //获取TYPE == 4  数据
    getTypeList() {
      this.AccordingList = [];
      //查询数组
      getBQuestionGroupName().then((resp) => {
        console.log("123123123123", resp);
        this.AccordingList = resp.data;
      });
    },
    //题库
    getQuestionBank(e) {
      listQuestionBank({ id: e }).then((res) => {
        console.log("题库显示", res);
        this.allBank = res.rows;
      });
    },
    //选择正确答案的按钮变化事件
    checkAnswer(checked, id) {
      if (checked) {
        if (this.addQuForm.questionType !== 2) {
          //单选或者判断
          //当前已经有一个正确的选择了
          this.addQuForm.answer.map((item) => {
            item.isTrue = false;
          });
          this.addQuForm.answer.map((item) => {
            if (item.id === id) item.isTrue = true;
          });
        } else {
          //多选 可以有多个答案
          this.addQuForm.answer.map((item) => {
            if (item.id === id) item.isTrue = true;
          });
        }
      } else {
        this.addQuForm.answer.map((item) => {
          if (item.id === id) item.isTrue = false;
        });
      }
    },
    //B型题选中后赋值
    assignment(id) {
      // console.log("B选中后",id);
      //查询赋值
      // var obj = this.AccordingList.find(item => item.id == id);
      // // console.log(obj);
      // this.addQuForm.quParentId = obj.quParentId;

      getQuestion(id, { type: false }).then((res) => {
        console.log(res);
        this.addQuForm.caseExamples = res.data.caseExamples;
        // this.addQuForm.questionContent = res.data.questionContent;
        this.addQuForm.answer = res.data.answer;
      });
    },

    //更新题目
    updateQu(id, type) {
      console.log("修改id", id);
      getQuestion(id, { type: true }).then((resp) => {
        console.log("修改内容", resp.data);
        if (resp.code === 200) {
          resp.data.answer.map((item) => {
            item.isTrue = item.isTrue === "true";
          });
          this.updateQuForm = resp.data;
          // this.updateQuForm.questionLevel = resp.data.questionType;
          //获取题库列表
          this.getQuestionBank(resp.data.questionLevel);

          this.caseExamplesBool = false;

          if (resp.data.questionType === 4) {
            this.According = true;

            var obj = this.AccordingList.find(function (item) {
              console.log("修改内容11111111", item);
              return item.quParentId === resp.data.quParentId ? item : 0;
            });
            console.log(obj);
            this.updateQuForm.quParentId = obj.id;

            this.updateQuForm.quParentId = resp.data.quParentId; //String(resp.data.data.questionId);
            this.updateQuForm.quGeneral = resp.data.quGeneral;
            this.caseExamplesBool = true;
          } else if (resp.data.questionType === 3) {
            this.caseExamplesBool = true;
          }

          //处理图片那个参数是个数组
          if (this.updateQuForm.images === null) this.updateQuForm.images = [];

          this.updateQuForm.answer.map((item) => {
            if (item.images === null) {
              item.images = [];
            }
          });
        }
      });

      this.updateQuTableVisible = true;
    },

    //更新时选择正确答案的按钮变化事件
    checkUpdateAnswer(checked, id) {
      if (checked) {
        if (this.updateQuForm.questionType !== 2) {
          //单选或者判断
          //当前已经有一个正确的选择了
          this.updateQuForm.answer.map((item) => {
            item.isTrue = false;
          });
          this.updateQuForm.answer.map((item) => {
            if (item.id === id) item.isTrue = true;
          });
        } else {
          //多选 可以有多个答案
          this.updateQuForm.answer.map((item) => {
            if (item.id === id) item.isTrue = true;
          });
        }
      } else {
        this.updateQuForm.answer.map((item) => {
          if (item.id === id) item.isTrue = false;
        });
      }
    },

    //提交更新表单
    updateQuestion() {
      console.log("提交更新表单", this.updateQuForm);

      if (this.updateQuFormquestionType === 4) {
        var countId = this.updateQuForm.quParentId;
        var obj = this.AccordingList.find(function (item) {
          return item.quParentId === countId ? item : 0;
        });
        this.updateQuForm.quGeneral = obj.quGeneral;
        //重新录入ID
        this.addQuForm.quParentId = obj.quParentId;
        this.addQuForm.quGeneral = obj.quGeneral;
      }
      //
      this.$refs["updateQuForm"].validate((valid) => {
        if (valid && this.updateQuForm.answer.some((item) => item.isTrue)) {
          //单选或者多选或者判断
          //保证答案的图片只有一张
          this.updateQuForm.answer.map((item) => {
            if (item.images.length > 1) {
              item.images.splice(0, item.images.length - 1);
            }
          });
          console.log("进入修改后台111111", this.updateQuForm);
          toUpdateQuestion(this.updateQuForm).then((res) => {
            if (res.code === 200) {
              this.updateQuTableVisible = false;
              this.$modal.msgSuccess("修改成功");
              this.getList();
            }
          });
        } else if (
          valid &&
          !this.updateQuForm.answer.some((item) => item.isTrue)
        ) {
          //无答案
          this.$message.error("必须有一个答案");
          return false;
        } else if (!valid) {
          this.$message.error("请填写必要信息");
          return false;
        }
      });
    },
  },
  computed: {
    titleList() {
      return this.$store.state.titleName.questionType
    }
  }
};
</script>
